package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Metric;
import cn.ibizlab.businesscentral.core.base.service.IMetricService;
import cn.ibizlab.businesscentral.core.base.filter.MetricSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"目标度量" })
@RestController("CentralApi-metric")
@RequestMapping("")
public class MetricResource {

    @Autowired
    public IMetricService metricService;

    @Autowired
    @Lazy
    public MetricMapping metricMapping;

    @PreAuthorize("hasPermission(this.metricMapping.toDomain(#metricdto),'iBizBusinessCentral-Metric-Create')")
    @ApiOperation(value = "新建目标度量", tags = {"目标度量" },  notes = "新建目标度量")
	@RequestMapping(method = RequestMethod.POST, value = "/metrics")
    public ResponseEntity<MetricDTO> create(@RequestBody MetricDTO metricdto) {
        Metric domain = metricMapping.toDomain(metricdto);
		metricService.create(domain);
        MetricDTO dto = metricMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.metricMapping.toDomain(#metricdtos),'iBizBusinessCentral-Metric-Create')")
    @ApiOperation(value = "批量新建目标度量", tags = {"目标度量" },  notes = "批量新建目标度量")
	@RequestMapping(method = RequestMethod.POST, value = "/metrics/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<MetricDTO> metricdtos) {
        metricService.createBatch(metricMapping.toDomain(metricdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "metric" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.metricService.get(#metric_id),'iBizBusinessCentral-Metric-Update')")
    @ApiOperation(value = "更新目标度量", tags = {"目标度量" },  notes = "更新目标度量")
	@RequestMapping(method = RequestMethod.PUT, value = "/metrics/{metric_id}")
    public ResponseEntity<MetricDTO> update(@PathVariable("metric_id") String metric_id, @RequestBody MetricDTO metricdto) {
		Metric domain  = metricMapping.toDomain(metricdto);
        domain .setMetricid(metric_id);
		metricService.update(domain );
		MetricDTO dto = metricMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.metricService.getMetricByEntities(this.metricMapping.toDomain(#metricdtos)),'iBizBusinessCentral-Metric-Update')")
    @ApiOperation(value = "批量更新目标度量", tags = {"目标度量" },  notes = "批量更新目标度量")
	@RequestMapping(method = RequestMethod.PUT, value = "/metrics/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<MetricDTO> metricdtos) {
        metricService.updateBatch(metricMapping.toDomain(metricdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.metricService.get(#metric_id),'iBizBusinessCentral-Metric-Remove')")
    @ApiOperation(value = "删除目标度量", tags = {"目标度量" },  notes = "删除目标度量")
	@RequestMapping(method = RequestMethod.DELETE, value = "/metrics/{metric_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("metric_id") String metric_id) {
         return ResponseEntity.status(HttpStatus.OK).body(metricService.remove(metric_id));
    }

    @PreAuthorize("hasPermission(this.metricService.getMetricByIds(#ids),'iBizBusinessCentral-Metric-Remove')")
    @ApiOperation(value = "批量删除目标度量", tags = {"目标度量" },  notes = "批量删除目标度量")
	@RequestMapping(method = RequestMethod.DELETE, value = "/metrics/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        metricService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.metricMapping.toDomain(returnObject.body),'iBizBusinessCentral-Metric-Get')")
    @ApiOperation(value = "获取目标度量", tags = {"目标度量" },  notes = "获取目标度量")
	@RequestMapping(method = RequestMethod.GET, value = "/metrics/{metric_id}")
    public ResponseEntity<MetricDTO> get(@PathVariable("metric_id") String metric_id) {
        Metric domain = metricService.get(metric_id);
        MetricDTO dto = metricMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取目标度量草稿", tags = {"目标度量" },  notes = "获取目标度量草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/metrics/getdraft")
    public ResponseEntity<MetricDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(metricMapping.toDto(metricService.getDraft(new Metric())));
    }

    @ApiOperation(value = "检查目标度量", tags = {"目标度量" },  notes = "检查目标度量")
	@RequestMapping(method = RequestMethod.POST, value = "/metrics/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody MetricDTO metricdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(metricService.checkKey(metricMapping.toDomain(metricdto)));
    }

    @PreAuthorize("hasPermission(this.metricMapping.toDomain(#metricdto),'iBizBusinessCentral-Metric-Save')")
    @ApiOperation(value = "保存目标度量", tags = {"目标度量" },  notes = "保存目标度量")
	@RequestMapping(method = RequestMethod.POST, value = "/metrics/save")
    public ResponseEntity<Boolean> save(@RequestBody MetricDTO metricdto) {
        return ResponseEntity.status(HttpStatus.OK).body(metricService.save(metricMapping.toDomain(metricdto)));
    }

    @PreAuthorize("hasPermission(this.metricMapping.toDomain(#metricdtos),'iBizBusinessCentral-Metric-Save')")
    @ApiOperation(value = "批量保存目标度量", tags = {"目标度量" },  notes = "批量保存目标度量")
	@RequestMapping(method = RequestMethod.POST, value = "/metrics/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<MetricDTO> metricdtos) {
        metricService.saveBatch(metricMapping.toDomain(metricdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Metric-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Metric-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"目标度量" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/metrics/fetchdefault")
	public ResponseEntity<List<MetricDTO>> fetchDefault(MetricSearchContext context) {
        Page<Metric> domains = metricService.searchDefault(context) ;
        List<MetricDTO> list = metricMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Metric-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Metric-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"目标度量" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/metrics/searchdefault")
	public ResponseEntity<Page<MetricDTO>> searchDefault(@RequestBody MetricSearchContext context) {
        Page<Metric> domains = metricService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(metricMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

